<template>
  <div class="wrapper">
    <div>
      <div class="flex">
        <el-button type="primary" size="mini" @click="handlePrint()">输出JSON</el-button>
        <importJson :store="3" @handleImport="handleImport"></importJson>
      </div>
      <el-table :data="tableData" highlight-current-row @current-change="handleCurrentChange" border align="left"
        style="width: 800px;margin-right:20px" height="600">
        <el-table-column label="工艺ID" width="160">
          <template slot-scope="scope">
            <el-select size="mini" v-model="scope.row.ID" placeholder="请选择">
              <el-option v-for="(item, k) in enSTrackControl" :key="item.key" :label="k" :value="item.key"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="工艺名称" width="160">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.name" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="阶段组" width="160">
          <template slot-scope="scope">
            <el-select size="mini" multiple v-model="scope.row.StageIDs" placeholder="请选择">
              <el-option v-for="item in enSTrackStage" :key="item.StageID" :label="item.name" :value="item.StageID">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="调试单元架号" width="160">
          <template slot-scope="scope">
            <el-input size="mini" v-model.number="scope.row.OrderHostNo" :controls="false" :min="0" :max="65535">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="支持架型" width="180">
          <template slot-scope="scope">
            <el-select size="mini" multiple v-model="scope.row.shieldTypeOpt" placeholder="请选择">
              <el-option v-for="item in enShieldType" :key="item.key" :label="item.name" :value="item.key"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="220" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleUpdata(scope.row)" type="text" size="small">更新</el-button>
            <el-button @click="handleShowStage(scope.row)" type="text" size="small">展示阶段闭环</el-button>
            <el-button @click="handleSetCfgSTrackStage(scope.row)" type="text" size="small">动作配置</el-button>
            <el-button @click="handleCollection(scope.row)" type="text" size="small">收藏</el-button>
            <el-button @click="handleSortStage(scope.row,scope.$index)" type="text" size="small">阶段排序</el-button>
            <el-button @click="handleDelete(scope.row,scope.$index)" type="text" size="small">删除</el-button>
            <el-button @click="handleExportCfgSTrackRunner(scope.row,scope.$index)" type="text" size="small">
              导出CfgSTrackRunner</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-card class="box-card" style="width:220px;">
      <div slot="header" class="wrapper flex_center">
        <div style="margin-right:12px">工具栏</div>
        <div>
          <el-button type="primary" size="mini" circle icon="el-icon-plus" @click="handleClickAdd"></el-button>
          <el-button type="primary" size="mini" circle icon="el-icon-edit" @click="showEditor = !showEditor">
          </el-button>
          <el-button type="primary" size="mini" circle icon="el-icon-delete" @click="showDelete = !showDelete">
          </el-button>
        </div>
      </div>
      <div v-for="(item, k) in toolsList" :key="k" class="card_item">
        <div class=" ">
          <el-button type="warning" size="mini" circle icon="el-icon-star-on"></el-button>
          <el-popconfirm @confirm="handlePushToolToTable(item)" title="确定增加这个工艺么？">
            <el-button slot="reference" size="mini" round>{{ item.name }}</el-button>
          </el-popconfirm>
        </div>
        <div>
          <el-button type="primary" size="mini" circle icon="el-icon-edit" v-if="showEditor"
            @click="handleClickEditor(item, k)"></el-button>
          <el-button type="primary" size="mini" circle icon="el-icon-delete" v-if="showDelete"
            @click="handleClickDelete(item, k)"></el-button>
        </div>
      </div>
    </el-card>
    <el-dialog :title="dialogTitle ? '添加工具项' : '更改工具项'" :visible.sync="dialogVisible" width="50%">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="工艺ID" :rules="[{ required: true, message: '请输入', trigger: 'blur' },]">
          <el-select v-model="form.ID" placeholder="请选择">
            <el-option v-for="item in enSTrackControl" :key="item.key" :label="item.name" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工艺名称" :rules="[{ required: true, message: '请输入', trigger: 'blur' },]">
          <el-input v-model="form.name" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="阶段组" :rules="[{ required: true, message: '请输入', trigger: 'blur' },]">
          <el-select v-model="form.StageIDs" multiple placeholder="请选择">
            <el-option v-for="item in enSTrackStage" :key="item.StageID" :label="item.name" :value="item.StageID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调试单元架号" :rules="[{ required: true, message: '请输入', trigger: 'blur' },]">
          <el-input-number v-model="form.OrderHostNo" :controls="false" :min="0" :max="65535"></el-input-number>
        </el-form-item>
        <el-form-item label="支持类型" :rules="[{ required: true, message: '请输入', trigger: 'blur' },]">
          <el-select v-model="form.shieldTypeOpt" multiple placeholder="请选择">
            <el-option v-for="item in enShieldType" :key="item.key" :label="item.name" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-drawer :title="STrackIDs.name+'-阶段组'" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <div style="padding: 10px;">
        <div v-for="(item, k) in STrackIDs.StageIDs" :key="k" class=" card_item">
          <div>{{ STrackStage[item].name }}</div>
          <div>
            <el-button type="primary" size="mini" circle icon="el-icon-top" @click="handleClickUp(item, k)"
              v-if="k != 0">
            </el-button>
            <el-button type="primary" size="mini" circle icon="el-icon-bottom" @click="handleClickDown(item, k)"
              v-if="k != STrackIDs.StageIDs.length - 1"></el-button>
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog :title="STrackIDs.name" @opened="STrackIDsOpen" :visible.sync="STrackIDsVisable" width="50%">
      <div style="display: flex;">
        <div id="stageMount" style="flex: 1;">
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import vuedraggable from 'vuedraggable'
  import Sortable from 'sortablejs';
  import enShieldType from './data/enShieldType';
  import enSTrackControl from './data/enSTrackControl';
  // import enSTrackStage from './data/enSTrackStage';
  import exportJson from "./utils/exportJson.js"
  import InDB from './utils/initDB.js'
  import initX6 from "./utils/initX6.js"

  import importJson from "./components/importJson.vue"
  export default {
    components: {
      importJson
      // vuedraggable
    },
    data() {
      return {
        STrackIDsVisable: false,
        drawer: false,
        direction: 'rtl',
        enShieldType: enShieldType,
        enSTrackControl: enSTrackControl,
        enSTrackStage: [],
        showDelete: false,
        showEditor: false,
        dialogVisible: false,
        dialogTitle: false,
        form: {},
        toolsChangeKey: null,
        toolsList: [],
        tableData: [],
        selectRow: 0,
        STrackStage: {},
        STrackIDs: {}
      };
    },

    methods: {
      handleImport(r) {
        this.tableData = r
      },
      handleCollection(r) {
        let obj = JSON.parse(JSON.stringify(r))
        delete obj.id
        InDB.controllerTools.put({
          ...obj
        }).then(async () => {
          this.toolsList = await InDB.controllerTools.all()
        })
      },
      handleExportCfgSTrackRunner(r) {
        if (!r.hasOwnProperty('CfgSTrackRunner_id')) {
          return this.$message({
            type: 'info',
            message: '该工艺还未配置CfgSTrackRunner'
          });
        }
        InDB.CfgSTrackRunner.get(r.CfgSTrackRunner_id).then(res => {
          let info = res.data
          for (let i = 0; i < info.length; i++) {
            let RunnerIDs = info[i].actions.map(item => {
              return item.STrackID
            })
            for (let j = 0; j < info[i].fixedList.length; j++) {
              let items = info[i].fixedList[j]
              for (let k = 0; k < items.items.length; k++) {
                let keys = items.items[k]
                RunnerIDs.push(keys.STrackID)
              }
            }
            info[i].RunnerIDs = RunnerIDs
          }
          console.log(info);
          // exportJson(info, '12_STrackRunner')
        })
      },
      STrackIDsOpen() {
        this.initShow()
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            InDB.CfgSTrackControl.put({
              ...this.tableData[this.selectRow]
            }).then(res => {
              this.drawer = false
            })
          })
          .catch(_ => {});
      },
      handleShowStage(r, i) {
        this.STrackIDs = r
        this.STrackIDsVisable = true
      },
      handleSortStage(r, i) {
        this.STrackIDs = r
        this.drawer = true
      },
      async handleUpdata(r) {
        InDB.CfgSTrackControl.put({
          ...r
        }).then(async () => {
          this.tableData = await InDB.CfgSTrackControl.all()
        })
      },
      handleDelete(r, i) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          InDB.CfgSTrackControl.delete(r.id).then(async () => {
            this.tableData = await InDB.CfgSTrackControl.all()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleCurrentChange(v, i) {},
      handlePrint() {
        // exportJson(this.tableData, "14_STrackControl")
        let data = this.tableData.map((item, i) => {
          let obj = {
            ...item,
            Name: item.name,
            StageCount: item.StageIDs ? item.StageIDs.length : 0
          }
          return obj
        })
        exportJson(data, "14_STrackControl")
      },
      handleDelCfgSTrackStage(r, i) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(i, 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        console.log(i);
      },
      handleSetCfgSTrackStage(r) {
        this.$router.push({
          path: '/CfgSTrackRunner5',
          query: {
            id: r.id
          }
        });
      },
      handleClickEditor(r, k) {
        this.toolsChangeKey = k;
        this.form = {
          ...r
        };
        this.dialogTitle = false;
        this.dialogVisible = true;
      },
      onCancel() {
        this.form = {}
        this.dialogVisible = false
      },
      async onSubmit() {
        let result = await InDB.controllerTools.put({
          ...this.form
        })
        this.toolsList = await InDB.controllerTools.all()
        this.dialogVisible = false;
      },
      async handleClickDelete(r, k) {
        this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(async () => {
            InDB.controllerTools.delete(r.tools_id).then(res => {
              this.toolsList.splice(k, 1);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      },
      async handlePushToolToTable(r) {
        InDB.CfgSTrackControl.put({
          ...r
        }).then(async () => {
          this.tableData = await InDB.CfgSTrackControl.all()
        })
      },
      handlePushTable(r) {
        console.log(r);
        // this.tableData.push(r);
      },
      handleClickAdd() {
        this.dialogTitle = true;
        this.form = {};
        this.dialogVisible = true;
      },
      handleClickUp(r, k) {
        if (k == 0) {
          return;
        }
        this.tableData[this.selectRow].StageIDs[k] = this.tableData[this.selectRow].StageIDs.splice(k - 1, 1, this
          .tableData[this.selectRow].StageIDs[k])[0];
      },
      handleClickDown(r, k) {
        if (k == this.tableData[this.selectRow].StageIDs - 1) {
          return;
        }
        this.tableData[this.selectRow].StageIDs[k] = this.tableData[this.selectRow].StageIDs.splice(k + 1, 1, this
          .tableData[this.selectRow].StageIDs[k])[0];
      },
      initShow() {
        this.graph = initX6.initMount({
          node: "stageMount",
          height: 250,
          scroller: true
        })
        this.updataGraph()
      },
      updataGraph() {
        let list = this.restructuringList()
        this.graph.fromJSON(list)
      },
      restructuringList() {
        let data = {
          nodes: [],
          edges: []
        }
        data.nodes = this.STrackIDs.StageIDs.map((item, i) => {
          let obj = {};
          let name = this.STrackStage[item].name
          obj = {
            x: 50 + i * 150,
            y: 50,
            id: item,
            width: 80,
            height: 40,
            attrs: {
              body: {
                // fill: '#2ECC71', // 背景颜色
                stroke: '#000', // 边框颜色
              },
              label: {
                text: name, // 文本
                fill: '#333', // 文字颜色
                fontSize: 13, // 文字大小
              },
            },
            ...item,
          };
          return obj;
        });
        data.edges = this.STrackIDs.StageIDs.map((item, i) => {
          if (i == this.STrackIDs.StageIDs.length - 1) {
            let obj = {
              source: item, // 起始点 id
              target: this.STrackIDs.StageIDs[0], // 目标点 id
              vertices: [{
                x: 50 + i * 150 + 40,
                y: 200
              }, {
                x: 50 + 40,
                y: 200
              }, ],
            };
            return obj;
          }
          let obj = {
            source: item,
            target: this.STrackIDs.StageIDs[i + 1]
          };
          return obj;
        });
        console.log(data);
        return data
      },
    },
    async created() {
      let stageList = await InDB.STrackStages.all()
      if (stageList.length) {
        this.enSTrackStage = stageList.map(item => {
          this.STrackStage[item.StageID] = {
            ...item
          }
          return item
        })
      }
      this.toolsList = await InDB.controllerTools.all()
      this.tableData = await InDB.CfgSTrackControl.all()
    },
    mounted() {},
  };
</script>

<style scoped>
  .flex {
    display: flex;
  }

  .flex_center {
    align-items: center;
  }

  .wrapper {
    display: flex;
    /* align-items: center; */
    /* justify-content: center; */
    width: 100%;
  }

  .card_item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 0;
    font-size: 12px;
    border-bottom: 1px solid #f6f6f6;
  }

  .card_item+.card_item {
    margin-top: 8px;
  }
</style>
